package com.pms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pms.constant.MessageConstant;
import com.pms.dto.ComplaintPageQueryDTO;
import com.pms.dto.ComplaintSaveDTO;
import com.pms.entity.Complaint;
import com.pms.entity.Owner;
import com.pms.exception.NotFoundException;
import com.pms.mapper.ComplaintMapper;
import com.pms.mapper.OwnerMapper;
import com.pms.result.PageResult;
import com.pms.service.ComplaintService;
import com.pms.vo.ComplaintPageQueryVO;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ComplaintServiceImpl implements ComplaintService {

    @Autowired
    private ComplaintMapper complaintMapper;
    @Autowired
    private OwnerMapper ownerMapper;

    /**
     * 新增投诉
     * @param complaintSaveDTO
     */
    public void save(ComplaintSaveDTO complaintSaveDTO) {
        Owner owner=ownerMapper.getByNameAndPhone(complaintSaveDTO.getOwnerName(),complaintSaveDTO.getPhone());
        if(owner==null){
            throw new NotFoundException(MessageConstant.OWNER_NOT_EXIST);
        }

        Complaint complaint=new Complaint();
        BeanUtils.copyProperties(complaintSaveDTO,complaint);
        complaint.setOwnerId(owner.getId());
        complaint.setCreateTime(LocalDateTime.now());
        complaintMapper.save(complaint);
    }

    /**
     * 投诉分页查询
     * @param complaintPageQueryDTO
     * @return
     */
    public PageResult page(ComplaintPageQueryDTO complaintPageQueryDTO) {
        PageHelper.startPage(complaintPageQueryDTO.getPage(), complaintPageQueryDTO.getPageSize());
        Page<ComplaintPageQueryVO> page=complaintMapper.page(complaintPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            complaintMapper.delete(id);
        }
    }
}
